package ltd.hxya.novel.crawl.handler;

import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import ltd.hxya.novel.common.bean.ResultEnum;
import ltd.hxya.novel.common.constant.redis.RedisConstant;
import ltd.hxya.novel.common.exception.NovelGlobalException;
import ltd.hxya.novel.common.utils.CrawlUtils;
import ltd.hxya.novel.common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Component
@Slf4j
public class CrawlHandler {

    @Autowired
    private RedisUtils redisUtils;

    public String crawlBody(String url) throws IOException {
        String randomIp = getRandomIp();
        log.info("使用的ip为："+randomIp);
        String body = CrawlUtils.entityToString(url, randomIp);
        return body;
    }

    public String getRandomIp(){
        Map<String, Integer> ipMap = redisUtils.get(RedisConstant.IP_POOL_KEY, new TypeReference<Map<String, Integer>>() {
        });
        if (CollectionUtils.isEmpty(ipMap)){
            throw new NovelGlobalException(ResultEnum.NOT_AVAILABLE_IP.getCode(), ResultEnum.NOT_AVAILABLE_IP.getMsg());
        }
        List<String> ipList = new ArrayList<>();
        ipMap.forEach((key,value)->{
            ipList.add(key+":"+value);
        });
        Random random = new Random();
        int index = random.nextInt(ipList.size());
        return ipList.get(index);
    }
}
